package org.springblade.modules.sga.service.impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.json.XML;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.isoftstone.sign.SignGeneration;
import org.springblade.common.tool.AESUtil;
import org.springblade.common.tool.HttpUtil;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.DateTimeUtil;
import org.springblade.core.tool.utils.RedisUtil;
import org.springblade.modules.policy.entity.Policy;
import org.springblade.modules.sga.mapper.SgaPolicyMapper;
import org.springblade.modules.sga.service.ISgaPolicyService;
import org.springblade.modules.sga.vo.SgaHotPolicyVO;
import org.springblade.modules.sga.vo.SgaPolicyVO;
import org.springblade.modules.sga.vo.SgaRelatedPolicyVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;

@Service
public class SgaPolicyServiceImpl extends BaseServiceImpl<SgaPolicyMapper, Policy> implements ISgaPolicyService {
	@Value("${hbzw.appKey}")
	private String appKey;
	@Value("${hbzw.secretKey}")
	private String secretKey;
	@Value("${hbzw.url}")
	private String URL;
	@Value("${hbzw.appId}")
	private String appId;
	@Value("${hbzw.sk}")
	private String sk;
	@Autowired
	private RedisUtil redisUtil;


	@Override
	public List<SgaPolicyVO> selectTop(int top) {
		return baseMapper.selectTop(top);
	}

	@Override
	public List<SgaHotPolicyVO> selectTopHot(int top) {
		return baseMapper.selectTopHot(top);
	}

	@Override
	public SgaPolicyVO getById(Long id) {
		return baseMapper.getById(id);
	}

	@Override
	public void increaseViewCount(Long id) {
		baseMapper.increaseViewCount(id);
	}

	@Override
	public IPage<SgaPolicyVO> selectPage(IPage<SgaPolicyVO> page, Integer policyType, Long levelId, Character industryType, String policyName) {
		return page.setRecords(baseMapper.selectPolicyPage(policyType, levelId, industryType, policyName, page));
	}

	@Override
	public IPage<SgaPolicyVO> selectPushPage(IPage<SgaPolicyVO> page, Boolean isPrecisePush, String enterpriseSpecial) {
		return page.setRecords(baseMapper.selectPushPolicyPage(isPrecisePush, enterpriseSpecial, page));
	}

	@Override
	public Integer countPolicy() {
		return baseMapper.countPolicy();
	}

	@Override
	public List<SgaRelatedPolicyVO> selectRelatedPolicy(String policyIds) {
		return baseMapper.selectRelatedPolicy(policyIds);
	}

	@Override
	public Object getEnvironmentSymbol(String certificateNumber, String enterpriseName, String unifyCode) {
		String timestamp = DateUtil.format(new Date(), "yyyyMMddHHmmss");
		String url = "http://59.208.244.246/irsp/openApi/kjbGxjsqyzsInfo/v1";
		HttpRequest request = new HttpRequest(url);

		Map<String, Object> map = new HashMap<>();
		map.put("serviceId", "ff8080817fdab0b4017fddd0e65410e2");
//			map.put("ak","efb7bca77311455683f00c1ae8078832");
		map.put("ak", "5a2842eb120447b88eeb05ed36da1d62");
		map.put("appId", "D01DB5BA5EB843F49EC379E7FA604F59");
		map.put("timestamp", timestamp);
		map.put("certificateNumber", certificateNumber);
		map.put("enterpriseName", enterpriseName);
		map.put("unifyCode", unifyCode);
		map.put("method", "post");
//			map.put("dataType","JSON");
//			map.put("startDate","1900-01-01 00:00:00");
//			map.put("endDate","2023-01-01 00:00:00");
		try {
			String sign = SignGeneration.generationSign(map, "59264d668b6449feac32282fb879bf1a");
			map.put("sign", sign);
			HttpResponse response = request.form(map).execute(true);
			System.out.println("10.responseBody=" + response.body());
			JSONObject jsonObject = JSONUtil.parseObj(response.body());
			String xmlData = jsonObject.get("data").toString();
			Object jsonData = XML.toJSONObject(xmlData).get("ROOT");
			System.out.println("11.jsonData=" + jsonData.toString());
//			Object gqData = JSONUtil.parseObj(jsonData).get("gqData");
//			System.out.println("12.data=" + gqData.toString());
			return jsonData;
		} catch (Exception ignored) {
			return null;
		}
	}

	@Override
	public String getToken(Map<String, String> content) throws Exception {
		Object tiem=redisUtil.get("HBZW-token-time");
		if (redisUtil.get("HBZW-token-time") != null && DateTime.now().before(((DateTime) redisUtil.get("HBZW-token-time")).offset(DateField.DAY_OF_MONTH, 1))) {
			return redisUtil.get("HBZW-token").toString();
		} else {
			content.put("appKey", appKey);
			content.put("secretKey", secretKey);
			Map<String, String> map = new HashMap<>();
			map.put("appKey", appKey);
			map.put("serviceId", "ff8080818ad61b61018ad660c10f0021");
			map.put("ak", "5a2842eb120447b88eeb05ed36da1d62");
			map.put("timestamp", DateUtil.format(new Date(), "yyyyMMddHHmmss"));
			map.put("appId", appId);
			JSONObject contentObj = new JSONObject(content);
			String encStr = AESUtil.Encrypt(contentObj.toString(), secretKey).replace("\n", "").replace("\r", "");
			map.put("enInfor", encStr);
			map.put("sign", SignGeneration.generationSign(map, sk));
			String res = HttpUtil.doPostXXX(URL + "/jksqpzhqfw/v1", map);
			JSONObject resJson = JSONUtil.parseObj(JSONUtil.parseObj(res).get("data"));
			String str = AESUtil.Decrypt((resJson.get("data").toString().replace("\n", "")), secretKey);
			JSONObject json = JSONUtil.parseObj(str);
			if (json.isEmpty()) {
				return "";
			} else {
				redisUtil.set("HBZW-token", json.get("token").toString());
				redisUtil.set("HBZW-token-time", DateTime.now());
				return json.get("token").toString();
			}
		}
	}

	@Override
	public String getQrCode(String token,String transactorName,String transactorIdCard) throws Exception {
		Map<String, String> content = new HashMap<>();
		content.put("applyContent", "码上补贴");
		content.put("sceneCode","1156277357853233152");
		content.put("relatedItemCode", "T114212225597241731004");
		content.put("relatedItemName", "咸宁市企心协力系统");
		content.put("thirdSystemInfo", "{\n" +
			"\"thirdSystemId\": \"421200T001\",\n" +
			"\"thirdSystemName\": \"咸宁市企心协力系统\"\n" +
			"}");
		content.put("applyWindowInfo", "{\n" +
			"\"windowId\": \"001W001\",\n" +
			"\"windowName\":\"企心协力网上平台\"\n" +
			"}");
		content.put("materialContent", "[{" +
			"\"materialName\": \"材料名称\"," +
			"\"data\": [{" +
			"\"certificateType\": \"中华人民共和国居民身份证\"," +
			"\"certificateTypeCode\": \"11100000000013127D001\"" +
			"}," +
			"{\"certificateType\": \"营业执照\"," +
			"\"certificateTypeCode\": \"11100000MB0143028R001\"" +
			"}" +
			"]}]");
		content.put("areaCode", "421200");
		content.put("certLibAccountId", "111421200747657174T.019");
		content.put("transactorType", "1");
		content.put("transactorName", transactorName);
		content.put("transactorIdCard", transactorIdCard);


		content.put("token", token);
		content.put("serviceId", "ff8080818ad61b61018b0846240c5af7");
		content.put("appKey", appKey);
		content.put("ak", "5a2842eb120447b88eeb05ed36da1d62");
		content.put("timestamp", DateUtil.format(new Date(), "yyyyMMddHHmmss"));
		content.put("appId", appId);

		content.put("sign", SignGeneration.generationSign(content, sk));
		for (String key : content.keySet()) {
			System.err.println(key + ":" + content.get(key));
		}
		String res=HttpUtil.doPostXXX(URL + "/bsmsqfw/v1", content);
		JSONObject json = JSONUtil.parseObj(JSONUtil.parseObj(res).get("data"));
		if ("00000".equals(JSONUtil.parseObj(json.get("head")).get("status").toString())) {
			return JSONUtil.parseObj(json.get("data")).get("content").toString();
		} else {
			return "获取失败，状态码:" + JSONUtil.parseObj(json.get("head")).get("status");
		}
	}

	@Override
	public String getAuthCode(String token, String qrCode) throws Exception{
		Map<String, String> content = new HashMap<>();
		content.put("token", token);
		content.put("qrCode", qrCode);
		content.put("serviceId", "ff8080818ad61b61018ad65dac79000f");
		content.put("appKey", appKey);
		content.put("ak", "5a2842eb120447b88eeb05ed36da1d62");
		content.put("timestamp", DateUtil.format(new Date(), "yyyyMMddHHmmss"));
		content.put("appId", appId);

		content.put("sign", SignGeneration.generationSign(content, sk));
		String res=HttpUtil.doPostXXX(URL + "/hqyzpzsqztfw/v1", content);
		JSONObject json = JSONUtil.parseObj(JSONUtil.parseObj(res).get("data"));
		if ("00000".equals(JSONUtil.parseObj(json.get("head")).get("status").toString())) {
			if ("NOT_AUTH".equals(JSONUtil.parseObj(json.get("data")).get("authStatus").toString())) {
				return JSONUtil.parseObj(json.get("data")).get("authStatusMessage").toString();
			}
			return JSONUtil.parseObj(json.get("data")).get("authCode").toString();
		} else {
			return "获取失败，状态码:" + JSONUtil.parseObj(json.get("head")).get("status");
		}

	}

	@Override
	public String getCertificateList(String token, String authCode) throws Exception{
		Map<String, String> content = new HashMap<>();
		content.put("token", token);
		content.put("authCode", authCode);
		content.put("serviceId", "ff8080818ad61b61018ad65bcbf70006");
		content.put("appKey", appKey);
		content.put("ak", "5a2842eb120447b88eeb05ed36da1d62");
		content.put("timestamp", DateUtil.format(new Date(), "yyyyMMddHHmmss"));
		content.put("appId", appId);

		content.put("sign", SignGeneration.generationSign(content, sk));

		JSONObject json = JSONUtil.parseObj(JSONUtil.parseObj(HttpUtil.doPostXXX(URL + "/hqsqzzqdfw/v1", content)).get("data"));
		if ("00000".equals(JSONUtil.parseObj(json.get("head")).get("status").toString())) {
			return JSONUtil.parseObj(json.get("data")).get("certificateList").toString();
		} else {
			return "获取失败，状态码:" + JSONUtil.parseObj(json.get("head")).get("status");
		}

	}
	@Override
	public void downloadFileByPolicyService(String certificateIdentifier,String authCode,String token, HttpServletResponse response)throws Exception{
		Map<String, String> map = new HashMap<>();
		map.put("serviceId", "ff8080818ad61b61018b084d18525b0a");
		map.put("ak", "5a2842eb120447b88eeb05ed36da1d62");
		map.put("appId", appId);
		map.put("timestamp", DateUtil.format(new Date(), "yyyyMMddHHmmss"));
		map.put("method","GET");

		Map<String, String> content = new HashMap<>();
		content.put("certificateIdentifier", certificateIdentifier);
		content.put("token", token);
		content.put("authCode", authCode);
		content.put("appKey", appKey);
		content.put("timestamp", DateUtil.format(new Date(), "yyyyMMddHHmmss"));
		content.put("appId", appId);
		map.put("otherParams", URLEncoder.encode(URLEncoder.encode(JSONUtil.toJsonStr(content))));
		map.put("sign", SignGeneration.generationSign(map, sk));
//		for (String key : content.keySet()) {
//			System.err.println(key + ":" + content.get(key));
//		}
		HttpUtil.doGetFile("http://59.208.244.246:80/irsp/fileStream/download",map,response);
//		String res=HttpUtil.doPostXXX("http://59.208.244.246:80/irsp/fileStream/download",content);
//		JSONObject jsonObject = JSONUtil.parseObj(res);
//		response.setContentType("application/pdf");
//		try {
//			BufferedInputStream inputStream = FileUtil.getInputStream("D:\\Users\\Admin\\Downloads\\医疗器械唯一标识管理信息系统数据共享API标准文档V2.2-20230617 (1).pdf");
//			byte[] data = IoUtil.readBytes(inputStream);
////			byte[] data = jsonObject.get("data").toString().getBytes();
//			IoUtil.write(response.getOutputStream(), true, data);
//		} catch (IOException e) {
//
//		}
	}

	@Override
	public String getBase64(String certificateIdentifier,String authCode,String token)throws Exception{
		Map<String, String> content = new HashMap<>();
		content.put("certificateIdentifier", certificateIdentifier);
		content.put("token", token);
		content.put("authCode", authCode);
		content.put("serviceId", "ff8080818ad61b61018b085137805b23");
		content.put("relatedItemCode", "T114212225597241731004");
		content.put("relatedItemName", "咸宁市企心协力系统");
		content.put("appKey", appKey);
		content.put("ak", "5a2842eb120447b88eeb05ed36da1d62");
		content.put("timestamp", DateUtil.format(new Date(), "yyyyMMddHHmmss"));
		content.put("appId", appId);
		content.put("sign", SignGeneration.generationSign(content, sk));
		String response=HttpUtil.doPost(URL + "/zztpbase64hqfw/v1", content);
		JSONObject json = JSONUtil.parseObj(JSONUtil.parseObj(response).get("data"));
		if (json.containsKey("head")&& JSONUtil.parseObj(json.get("head")).containsKey("status") && "0".equals(JSONUtil.parseObj(json.get("head")).get("status").toString())) {
			return JSONUtil.parseObj(json.get("data")).get("imageBase64s").toString();
		} else {
//			return "获取失败，状态码:" + JSONUtil.parseObj(json.get("head")).get("status");
			return "获取失败:" + response;
		}
	}
}
